package com.example.wszb.utils;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;

public class HttpUrlConnectionUtils {

    private static final String DEF_CHATSET = "UTF-8";
    private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    private static int DEF_CONN_TIMEOUT = 30000;
    //private static String strUrl = "http://47.101.173.130:8080/wszb";  // 服务器网址
    private static String strUrl = "http://10.200.98.173:8080/";    // 本地服务器网址，不能使用localhost:8080


    // 传入的参数为要进行的服务，例如http://10.200.98.173:8080/login及进行登录操作，register则是注册操作还没进行开发
    public static String doPOST(JSONObject jsonObject, String tempUrl) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String result = "{\"result\":\"0\",\"msg\":\"连接失败\"}";
        try {
            // 获取连接
            URL url = new URL(strUrl+tempUrl);
            System.out.println(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");//请求的类型
            conn.setDoInput(true);
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();

            // 发送数据
            conn.getOutputStream().write(String.valueOf(jsonObject).getBytes());//把数据以流的方式写给服务器。

            // 获取返回的数据，String类型的json格式字符串
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            //BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            String strRead = null;
            StringBuffer sb = new StringBuffer();
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            result = sb.toString();
        } catch (Exception e) {
// TODO: handle exception
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }

}
